import cx_Oracle
import monitor.check_oracle_sql as oracle_sql
import utils.config_util as config_util


class CheckOracle:
    def __init__(self, user, password, host, sid):
        self.user = user
        self.password = password
        self.host = host
        self.sid = sid

    def check_oracle(self):
        # start = time.time()
        check = {}
        try:
            connection = cx_Oracle.connect(self.user, self.password, self.host + "/" + self.sid)
            """:type cx_Oracle.Connection"""
        except:
            return check
        cursor = connection.cursor()
        """:type cx_Oracle.Cursor"""
        sqls = oracle_sql.sql
        for key in sqls.keys():
            if sqls[key] != "" and sqls[key] is not None:
                # start_temp = time.time()
                check[key] = self.__execute(cursor, sqls[key])
                # end_temp = time.time()
                # print(key+":"+str(end_temp-start_temp))
        cursor.close()
        connection.close()
        # end = time.time()
        # print(end-start)
        return check


    def __execute(self, cursor, sql):
        """
        :return: 返回执行结果
        """
        cursor.execute(sql)
        result = []
        row_name = []
        for row in cursor.description:
            row_name.append(row[0])
        for row in cursor.fetchall():
            temp_dict = {}
            for i in range(len(row)):
                temp_dict[row_name[i]] = row[i]
            result.append(temp_dict)
        return result


def check_local_oracle():
    host = config_util.get_config("oracle", "host")
    sid = config_util.get_config("oracle", "sid")
    user = config_util.get_config("oracle", "user")
    password = config_util.get_config("oracle", "password")
    oracle = CheckOracle(user, password, host, sid)
    return oracle.check_oracle()


if __name__ == '__main__':
    a = CheckOracle("electriclicense", "electriclicense", "192.168.168.4", "signon")
    print(a.check_oracle())
